<template>
  <div>
    <el-card shadow="hover" style="margin-bottom: 20px">
      <div class="flex-warp">
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-input
              placeholder="请输入考试名称"
              size="small"
              suffix-icon="el-icon-search"
              v-model="listQueryParam.examName"
            >
            </el-input>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-input placeholder="请输入学生姓名"
                      size="small"
                      suffix-icon="el-icon-search"
                      v-model="listQueryParam.name"
            >
            </el-input>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button size="small" icon="el-icon-search" @click="search">搜索</el-button>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button type="primary" size="small" icon="el-icon-refresh-right" @click="refresh">刷新</el-button>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box" style="display: flex;align-items: center">
            <!-- <a href="https://code-graden-server-dev.oss-cn-beijing.aliyuncs.com/example.xls" target="_blank" style="color: red">excel题目下载</a> -->
          </div>
        </div>
      </div>
    </el-card>
    <el-card shadow="hover" class="mt15">
      <el-table
        :data="tableData"
        stripe
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :data="props.row.examDetailDTOS"
              style="width: 100%"
            >
              <el-table-column
                prop="examName"
                label="考试名称"
                width="180"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="questionName"
                label="题目名称"
                align="center"
                width="180"
              >
              </el-table-column>
              <el-table-column
                prop="grade"
                align="center"
                label="我的分数"
              >
              </el-table-column>
              <el-table-column
                prop="questionGrade"
                align="center"
                label="问题分数"
              >
              </el-table-column>
              <el-table-column
                prop="rightAnswer"
                label="正确答案"
                align="center"
                width="180"
              >
              </el-table-column>
              <el-table-column
                prop="answer"
                align="center"
                label="学生填写答案"
              >
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          label="学生姓名"
        >
        </el-table-column>
        <el-table-column
          prop="examName"
          align="center"
          label="考试名称"
        >
        </el-table-column>
        <el-table-column
          prop="examScore"
          align="center"
          label="考试成绩"
        >
        <template slot-scope="scope">
          <!-- 根据阅卷情况动态显示成绩 -->
          {{ scope.row.markingStatus === "未阅卷" ? "待阅卷" : scope.row.examScore }}
        </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="阅卷情况"
        >
          <template slot-scope="scope">
            <el-button 
              class="marking-status-button flip-button"
              size="mini" 
              :type="scope.row.markingStatus === '已阅卷' ? 'success' : 'default'"
              plain
            >
              {{ scope.row.markingStatus }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="endTime"
          align="center"
          label="考试截止时间"
        >
        </el-table-column>
        <el-table-column
          prop="takeTime"
          align="center"
          label="考试参加时间"
        >
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQueryParam.current"
        :limit.sync="listQueryParam.pageSize"
        @pagination="getTableDataList"
      />
    </el-card>
  </div>
</template>

<script>
import {
  getList,
  insert,
  update,
  get,
  del,
  getExamDate,
  getStudentDate,
  saveData,
  saveNewData
} from '@/api/ExamStudent/index'
import {getList as getRightAnswer} from '@/api/Questions/index'
import Pagination from '@/components/Pagination'
import { tableUtil } from '@/mixins/table'
import { Message } from 'element-ui'
import uploadImg from '@/components/ImageUpload'
import ImgPreview from '@/components/ImgPreview'
import FileUpload from '@/components/FileUpload'

export default {
  mixins: [tableUtil],
  components: {
    FileUpload,
    Pagination,
    uploadImg,
    ImgPreview
  },
  data() {
    return {
      type: localStorage.getItem('examType'),
      listQueryParam: {
        current: 1,
        pageSize: 5
      },
      excelUrl: '',
      dialogVisible: false,
      showExcel: false,
      formData: {},
      rules: {
        examId: [
          { required: true, message: '请选择所属考试', trigger: 'change' }
        ],
        studentId: [
          { required: true, message: '请选择所属学生', trigger: 'change' }
        ]
      },
      examIdOptions: [],
      studentIdOptions: [],
      currentStudent: {}
    }
  },
  mounted() {
    this.getTableDataList();
    this.$nextTick(() => {
      // 动态添加翻转动画类
      const buttons = this.$el.querySelectorAll('.marking-status-button');
      buttons.forEach(button => {
        button.classList.add('flip-button');
      });
    });
  },
  methods: {
    uploadExcel() {
      this.dialogVisible = true
    },
    getTableDataList() {
      if (this.type == 2) {
        this.listQueryParam.studentId = localStorage.getItem('examId')
      }
      getList(this.listQueryParam).then((res) => {
        this.total = res.data.total
        this.tableData = res.data.records.map(record => {
          // 计算总成绩
          const examScore = record.examDetailDTOS.reduce((sum, detail) => {
            return sum + Number(detail.grade); // 将 grade 转换为数字
          }, 0);

          // 判断阅卷情况
          const markingStatus = record.examDetailDTOS.length > 0 ? "已阅卷" : "未阅卷";

          // 查询每个 questionId 对应的 rightAnswer
          const questionIds = record.examDetailDTOS.map(detail => detail.questionId);
          console.log("2222：", questionIds);

          // 使用 Promise.all 确保所有异步请求完成
          const getRightAnswerPromises = questionIds.map(questionId => {
            return getRightAnswer({ id: questionId }).then(answerRes => {
              if (answerRes && answerRes.data) {
                return { questionId, rightAnswer: answerRes.data.records[0].answer };
              }
              return { questionId, rightAnswer: '未找到答案' };
            });
          });

          return Promise.all(getRightAnswerPromises).then(results => {
            const questionIdToRightAnswerMap = new Map(results.map(result => [result.questionId, result.rightAnswer]));
            console.log("答案:", questionIdToRightAnswerMap);

            // 将 rightAnswer 字段加入到每个 examDetailDTOS 中
            const updatedExamDetailDTOS = record.examDetailDTOS.map(detail => {
              const rightAnswer = questionIdToRightAnswerMap.get(detail.questionId) || '未找到答案';
              return { ...detail, rightAnswer };
            });

            return { ...record, examScore, markingStatus, examDetailDTOS: updatedExamDetailDTOS };
          });
        });

        // 等待所有记录处理完成
        Promise.all(this.tableData).then(updatedTableData => {
          this.tableData = updatedTableData;
        });
      });
    },
    updateClick(row) {
      this.dialogTitle = '修改'
      get(row.id).then((res) => {
        this.formData = res.data
        this.addOrUpdateDialogVisible = true
      })
    },
    delByIds(ids) {
      del(ids).then((res) => {
        Message.success('删除成功')
        this.getTableDataList()
      })
    },
    saveData() {
      if (this.formData.id) {
        update(this.formData).then((res) => {
          Message.success('修改成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      } else {
        insert(this.formData).then((res) => {
          Message.success('添加成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      }
    }
  }
}
</script>
<style>
.marking-status-button {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 5px 15px;
  font-size: 14px;
  color: #666;
  background-color: #f5f5f5;
  transition: background-color 0.3s, color 0.3s;
}

.marking-status-button:hover {
  background-color: #e0e0e0;
}

.marking-status-button.success {
  color: #ffffff;
  background-color: #67c23a;
  border-color: #67c23a;
}

.marking-status-button.success:hover {
  background-color: #56b338;
  border-color: #56b338;
}

@keyframes flip {
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(180deg);
  }
  100% {
    transform: rotateY(360deg);
  }
}

.flip-button {
  animation: flip 1s forwards;
}
</style>